<style lang="scss" scoped>
.container {
  padding: 0 16px;
}

.el-select .el-select--small {
  display: block !important;
}
</style>

<!-- 页面布局-->
<template>
  <div class="table">
    <!-- 主体区 -->
    <div class="container">
      <div class="grid-data-box" style="width: 850px;">
        <div class="detailTitle fxrow" style="overflow: hidden;justify-content: space-between;margin-bottom: 5px;">
            <div class="fxrow fxsc" style="flex: 1;">
              <table>
                <tr>
                  <td>
                    <i class="el-icon-search"></i>
                  </td>
                  <td class="search_td">
                    <v-selectpage data="/rps/province/?isp=10010&pageRows=10&pageIndex=1" :params="{isp: '10010'}" :page-rows="10" key-field="provinceId" show-field="provinceName" :selected="parampters.provinceId" :result-format="resultFormat" :placeholder="parampters.provinceName || '省份'" v-model="parampters.provinceId" @values="changeProvince" @removed="clearParameters('province')">
								    </v-selectpage>
                  </td>
                  <td class="search_td">
                    <v-selectpage v-if="canChoseCity" :data="`/rps/city/?provinceId=${this.parampters.provinceId}`" :params="{provinceId: this.parampters.provinceId}" :page-rows="10" key-field="cityCode" show-field="cityName" :selected="parampters.cityCode" :result-format="resultFormat" :placeholder="parampters.cityName || '地市'" v-model="parampters.cityCode" @values="changeCity" @removed="clearParameters('city')">
                    </v-selectpage>
                    <el-select :disabled="true" v-else v-model="parampters.cityCode" placeholder="地市" clearable class="handle-input mr10">
                    </el-select>
                  </td>
                  <td class="search_td">
                    <el-select v-model="parampters.dnsegNum" clearable placeholder="号段" @focus="preSelDnesg" class="handle-input mr10">
                      <el-option v-for="item in dicts.dnseg" :key="item.dnsegNum" :label="item.dnsegNum" :value="item.dnsegNum">
                      </el-option>
                    </el-select>
                  </td>
                  <td class="search_td">
                    <el-input v-model="parampters.productName" clearable placeholder="产品名称" class="handle-input mr10"></el-input>
                  </td>
                </tr>
              </table>
            </div>
            <div>
              <el-button size="small" type="primary" @click="initFormData()">查询</el-button>
              <el-button size="small" v-if="actType == 'upd'||actType == 'add'" type="primary" :disabled="readOnly" @click="newItem()">新增</el-button>
            </div>
        </div>
        <div class="detailTitle fxrow" style="overflow: hidden;justify-content: space-between;">
          <div class="fxrow fxsc" style="flex: 1;line-height: 32px;">
            <div>制卡数量：{{cardNumTol}}</div>
          </div>
        </div>
        <el-table v-loading="tableLoading" :data="tableData" max-height="350" border style="width: 100%" ref="singleTable" highlight-current-row @row-dblclick="clickToView" :cell-style="{padding:'3px 0 !important'}">
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <el-table-column prop="cardNum" width="80" show-overflow-tooltip label="申请数量"></el-table-column>
            <el-table-column prop="provinceName" width="80" show-overflow-tooltip label="省份" align="center"></el-table-column>
            <el-table-column prop="cityName" width="80" show-overflow-tooltip label="地市"  align="center"></el-table-column>
            <el-table-column prop="productName" show-overflow-tooltip label="产品名称"></el-table-column>
            <el-table-column prop="cardFaceName" width="100" show-overflow-tooltip label="版面描述"></el-table-column>
            <el-table-column prop="dnsegNum" width="80" show-overflow-tooltip label="号段"></el-table-column>
            <el-table-column prop="spName" width="100" show-overflow-tooltip label="卡商"></el-table-column>
            <el-table-column label="操作" width="150" fixed="right" >
                <template slot-scope="scope">
                    <el-button size="small" @click="toUpd(scope.row)" :disabled="readOnly" type="primary">修改</el-button>
                    <el-button size="small" @click="toDel(scope.row)" :disabled="readOnly" style="margin-left: 10px;">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="navigate-box">
          <div class="pagination">
            <el-pagination background @current-change="handleCurrentChange" :total="parampters.totalCount" @size-change="handleSizeChange" :current-page.sync="parampters.pageIndex" :page-sizes="[20, 50, 100, 200]" :page-size="parampters.pageRows" layout="total, sizes, prev, pager, next"></el-pagination>
          </div>
        </div>
      </div>
     
      <!-- 表单区END -->
      <!-- 按钮操作区 -->
      <span slot="footer" class="form-btn-box" style="margin-top: 10px;">
        <el-button @click="cnacelForm()">取 消</el-button>
      </span>
      <!-- 按钮操作区END -->

    </div>
    <!-- 主体区END -->

    
  </div>
</template>
<script>
import applybatchUpdForm from "./applybatch_upd_form"
export default {
  data() {
    return {
      // 筛选条件
      parampters: {
        //查询参数
        pageRows: 20, //每页行数
        pageIndex: 1, //当前页
        pageCount: 0, //总页数
        totalCount: 0, //总记录数
        provinceId: "", //省份
        cityCode: "", //地市
        dnsegNum: "",
        starttime: "",
        endtime: "",
      },
      // 提交表单的loading设置标识
      fullscreenLoading: false,
      firstLoadedData: "{}",
      // 表单校验规则
      //所选记录id
      selectedId: "",
      //事物类型
      actType: "",
      // 表单只读状态
      readOnly: false,
      //字典集
      dicts: {},
      tableLoading: true,
      tableData: [],
      spNo: "",
      canSelDnseg: false, //未选择省市时，不可以选择号段
      canChoseCity: false,
      cardNumTol: 0
    };
  },
  props: {
    sourceData: {
      required: true
    }
  },
  // 进入页面加载数据
  mounted() {
    this.handleInitLoad();
  },
  methods: {
    /**
     * 组件初始化加载
     */
    handleInitLoad() {
      this.initSelectOptoins();
      this.initFormData();
    },

    /**
     * 初始加载字典选项
     */
    initSelectOptoins() {
      // this.loadSelectOptoins("province", {"isp":10010});
    },

    /**
     * 通用定义:下拉字典
     *  @augments dictKind 字典类型
     */
    loadSelectOptoins(dictKind, params) {
      let url = "/rps/" + dictKind + "/";
      this.$axios
      .get(url, {
        params: params,
        headers:{
            operator: this.$util.getLoginer().userid,
            withCredentials: true
        }
      })
      .then(res => {
        let data = res.data;
        if (data.success) {
          this.$set(this.dicts, dictKind, data.data.list);
        } else {
          this.$error( "查询失败" + data.message );
        }
      })
      .catch(err => {
        console.log(err);
      });
    },

    /**
     * 取消返回
     * @augments formName 表单名称
     */
    cnacelForm(formName) {
      this.$emit("ok", null);
    },

    /**
     * @augments val 页码
     * 切换页码操作
     */
    handleCurrentChange(val) {
      this.parampters.pageIndex = val;
      // 重新获取当前页码的数据
      this.initFormData();
    },

    /**
     * @augments val 每页显示条数
     * 每页显示条数修改
     */
    handleSizeChange(val) {
      // 修改每页显示条数
      this.parampters.pageRows = val;
      // 重新获取数据
      this.initFormData();
      this.getCardNumTol();
    },
    
    /**
     *初始化加载表单数据
     */
    initFormData() {
      this.selectedId = this.sourceData.seleid;
      this.actType = this.sourceData.actType;
      if (this.actType == "view") {
        // 查看状态 标识表单只读
        this.readOnly = true;
      }
      var url = "/rps/cardApplyDetail/";
      if ( this.actType != null && (this.actType == "upd" || this.actType == "view") ) {
        url += this.selectedId + "/?" + new Date().getTime();
        this.$axios
          .get(url, {
              params: this.parampters,
              headers: {
                operator: this.$util.getLoginer().userid,
                withCredentials: true
              }
            }
          )
          .then(res => {
            let data = res.data;
            if (data.success) {
              this.tableData = data.data.list;
              this.tableLoading = false;
              this.parampters.pageIndex =
                data.data.pageNum != undefined ? parseInt(data.data.pageNum) : 0;
              this.parampters.pageCount =
                data.data.totalPage != undefined ? parseInt(data.data.totalPage) : 0;
              this.parampters.totalCount =
                data.data.count != undefined ? parseInt(data.data.count) : 0;
              if(this.tableData != null && this.tableData != undefined && this.tableData.length > 0){
                this.spNo = this.tableData[0].spNo;
              }
              this.getCardNumTol();
            } else {
              this.tableLoading = false;
              this.$error(data.message);
            }
          })
          .catch(err => {
            this.tableLoading = false;
            console.log(err);
          });
      }
    },

    /**
     * 新增记录
     */
    newItem(){
      //页面参数
      var pageParam = {
        actType: "add",
        seleid: this.selectedId,
        seleSpNo: this.spNo
      };
      let commDialog = this.$dialog.commDialog(
        "编辑记录",
        applybatchUpdForm,
        pageParam,
        "700px",
        "410px"
      );
      commDialog.exec.then(resp => {
        if (resp.type == "ok") {
          this.initFormData();
        } else if (resp.type == "cancel") {
        }
      });
    },

    clickToView(rowData, column, event) {
			this.toView(rowData);
    },
    
    toView(row){
      //页面参数
      var pageParam = {
        actType: "view",
        item: row,
        seleid: this.selectedId,
        seleSpNo: this.spNo
      };
      let commDialog = this.$dialog.commDialog(
        "查看记录",
        applybatchUpdForm,
        pageParam,
        "700px",
        "410px"
      );
      commDialog.exec.then(resp => {
        if (resp.type == "ok") {
        } else if (resp.type == "cancel") {
        }
      });
    },

    toUpd(row){
      //页面参数
      var pageParam = {
        actType: "upd",
        item: row,
        seleid: this.selectedId,
        seleSpNo: this.parampters.totalCount == 1 ? null : this.spNo
      };
      let commDialog = this.$dialog.commDialog(
        "编辑记录",
        applybatchUpdForm,
        pageParam,
        "700px",
        "410px"
      );
      commDialog.exec.then(resp => {
        if (resp.type == "ok") {
          this.initFormData();
        } else if (resp.type == "cancel") {
        }
      });
    },

    toDel(row){
      let url = "/rps/cardApplyBatch/"+ this.selectedId +"/cardApplyDetail/";
      let formData = [];
      formData.push(row);
      this.$axios
        .delete(url, {
          data: formData
        }, {
          headers: {
            operator: this.$util.getLoginer().userid,
            withCredentials: true
          }
        })
        .then(res => {
          let data = res.data;
          // 关闭提交表单的loading
          this.fullscreenLoading = false;
          if (data.success) {
            this.$message({
              message: "删除记录成功.",
              type: "success"
            });
            this.initFormData();
          } else {
            this.$error(data.message);
          }
        })
        .catch(err => {
          this.fullscreenLoading = false;
        });
    },

    changeProvince(res){
      if(res && res.length > 0){
				let province = res[0];
        if(province.provinceCode != this.parampters.provinceCode){
          this.$set(this.parampters, "provinceCode", province.provinceCode);
          this.$set(this.parampters, "provinceName", province.provinceName);
          this.$set(this.parampters, "cityCode", "");
          this.$set(this.parampters, "cityName", "");
        }
				this.canChoseCity = true;
			}
    },

    changeCity(res){
      console.log("changeCity");
      if(res && res.length > 0){
        let city = res[0];
        if(city.cityCode != this.parampters.cityCode){
          this.$set(this.parampters, "cityName", city.cityName);
          this.$set(this.parampters, "cityCode", city.cityCode);
        }
        this.canSelDnseg = true;
      }
    },

    preSelDnesg(){
      if(!this.canSelDnseg){
        this.$error("请先选择省市，后选择号段");
      }else{
        let params = {
          provinceCode: this.parampters.provinceCode,
          cityCode: this.parampters.cityCode
        }
        this.loadSelectOptoins("dnseg", params);
      }
    },

    /**
		 * v-selectpage 格式化参数数据
		 */
		resultFormat(resp){
			let data = resp.data;
			 if(data.success){
				return {
					totalRow: data.data ? data.data.count : 0,
					list: data.data ? data.data.list : []
				};
			 } else {
				return {
					totalRow: 0,
					list: []
				};
			 }
    },
    
		clearParameters(name){
			if(name == "province"){
				this.$delete(this.parampters, "provinceCode");
				this.$delete(this.parampters, "provinceId");
				this.$delete(this.parampters, "provinceName");
				this.$delete(this.parampters, "cityCode");
				this.$delete(this.parampters, "cityName");
				this.canChoseCity = false;
			}else if(name == "city"){
				this.$delete(this.parampters, "cityCode");
				this.$delete(this.parampters, "cityName");
			}
    },
    
    getCardNumTol(tableData){
      this.$axios.get("/rps/cardApplyDetail/"+ this.selectedId +"/sumCardNum/", {
        params: this.parampters
      }).then(res => {
        let data = res.data;
        if(data.success){
          this.cardNumTol = data.data
        }
      })
    },

  }
};
</script>
